package com.example.main.job;

import com.example.main.entity.HistoryEntity;
import com.example.main.entity.ServicesEntity;
import com.example.main.service.HistoryService;
import com.example.main.service.ServicesService;
import com.example.main.utils.WechatUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 定时任务,对每一个微服务进行心跳测试
 */

@Log4j2
@Component
public class HeartbeatJob {
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    HistoryService historyService;

    @Autowired
    ServicesService servicesService;
    /**
     * 每15秒一次心跳测试
     */
//    @Scheduled(cron = "0/15 * * * * ?")
    public void execute() {
        /**
         * 1.获取数据库中需要监控的实例
         * 2.获取nacos中存活的实例
         * 3.a.进行比较,实例大于0是正常的,小于0不是正常的
         * 4.发生异常,启动异步,开始报警 把记录写到数据库
         */

        // 1.获取数据库中需要监控的实例
        List<ServicesEntity> observeds = servicesService.list();
        // 2.获取nacos中存活的实例
        List<String> survivals = discoveryClient.getServices();
        // 3.a.进行比较,实例大于0是正常的,小于0不是正常的
        for (ServicesEntity observed : observeds) {
            boolean alive = false;

            for (String survival : survivals) {
                if (survival.equalsIgnoreCase(observed.getServiceName())) {
                    List<ServiceInstance> instances = discoveryClient.getInstances(survival);

                    if (instances.size() != 0) {
                        alive = true;

                        // 如果还不相信nacos 可以获取实例去请求心跳接口BaseController里面的接口
                    }
                }
            }
            /**
             * 实例不存在,调用企业微信API 报警
             */
            if (!alive) {
                log.error(observed.getServiceName() + "服务不存在实例！！！");
                // 调用企业微信API写在这儿
                String msg = observed.getServiceName() + "服务挂掉了";
                WechatUtils.sendMessage(msg);
                // 将报警记录写在数据库里
                HistoryEntity history = new HistoryEntity();
                history.setOccurenceTime(new Date());
                history.setServiceName(observed.getServiceName());
                historyService.save(history);
            }
        }
    }
}
